#pragma once

#include <iostream>
#include <vector>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;
static int count = 0;
class TaskManger
{
    public:
    TaskManger()
    {
        srand(time(nullptr));
        _tasks.push_back([]()->void
             { std::cout << "sub process[" << getpid() << " ] 执行访问数据库的任务\n"
                                    << std::endl; });
        _tasks.push_back([]()->void
              { std::cout << "sub process[" << getpid() << " ] 执行url解析\n"
                                    << std::endl; });
	    _tasks.push_back([]()->void
              { std::cout << "sub process[" << getpid() << " ] 执行加密任务\n"
                                    << std::endl; });
	    _tasks.push_back([]()->void
              { std::cout << "sub process[" << getpid() << " ] 执行数据持久化任务\n"
                                    << std::endl; });
    }
    int SelectTask()
    {
        return rand() % _tasks.size();
    }
    void Excute(unsigned long number)
    {
        if (number > _tasks.size() || number < 0)
            return;
        _tasks[number]();
    }
    ~TaskManger()
    {
    }
    
    private:
    std::vector<task_t> _tasks;
};

TaskManger tm;

void BeginWork()
{
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));//从标准输入流中读取任务编号
        if (n == sizeof(cmd))
        {
            tm.Excute(cmd);
        }
        else if (n == 0)//根据上篇文章所学，当read读0时，一定是父进程关闭了写端，换而言之，子进程也该退出啦
        {
            std::cout << "pid: " << getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
        }
    }
}